package ims.db.view.prodType;

import ims.beans.ProductType;
import ims.constants.IMSConstants;
import ims.db.AbstractDAO;
import ims.db.AbstractDbRequest;
import ims.db.AbstractDbResponse;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class ViewProdTypesDAO extends AbstractDAO {

	public ViewProdTypesDAO() throws ClassNotFoundException, SQLException {
		super();
	}

	@Override
	public AbstractDbResponse execute(AbstractDbRequest dbRequest) 
	{
		ViewProdTypesDbResponse response = new ViewProdTypesDbResponse();
		ViewProdTypesDbRequest request = (ViewProdTypesDbRequest)dbRequest;
        try 
        {
        	Statement stmt = conn.createStatement();
        	StringBuffer sql = new StringBuffer();
        	if(request.isViewAll())
        		sql.append("select prodTypeId,productType from ProductType order by prodTypeId");
        	else
        		sql.append("select prodTypeId,productType from ProductType where prodTypeId ='").append(request.getProdTypeId()).append("'");
        		
        	
    		ResultSet rset = stmt.executeQuery(sql.toString());
    		ArrayList <ProductType> prodTypes = new ArrayList <ProductType> ();
	        while (rset.next())
	        {
	        	ProductType prodType = new ProductType();
	        	prodType.setProdTypeId(rset.getString(1));
	            prodType.setProdType(rset.getString(2));
	            prodTypes.add(prodType);
	        }
	        if (request.isViewAll())
	        {
	        	String lastProdTypeId = prodTypes.get(prodTypes.size()-1).getProdTypeId().substring(2);
	        	int id = Integer.parseInt(lastProdTypeId);
	        	IMSConstants.PROD_TYPE_ID = ++id;
	        }
	        
	        response.setProdTypes(prodTypes);
	        rset.close();
            stmt.close();
            conn.close();
        } 
        catch (SQLException sqlEx)
        {
        	sqlEx.printStackTrace();
        }
        return response;
	}
}
